#include "header.h"

extern char CompressionServerIP[MAX_IPV4_IP_LEN];

void sendControlInfoAndFile(int clientIP, char *sendfile, char *file, int size)
{
	int ret, sockfd;
	struct nextHop nextHop;
	struct sockaddr_in SockAddr;

	strcpy(nextHop.filename, file);
	nextHop.clientIP = clientIP;
	nextHop.size = size;

	//sendControlInfo();
	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if (FAILURE == sockfd) {
		printf("Unable to create socket while sending control info to decryption server\n");
		ret = FAILURE;
		goto end;
	}

	memset(&SockAddr, 0, sizeof(SockAddr));
	SockAddr.sin_family = AF_INET;
	SockAddr.sin_port = htons(COMPRESSION_SERVER_TCP_PORT);

	inet_pton(AF_INET, CompressionServerIP, &SockAddr.sin_addr);

	ret = connect(sockfd, (const void *)&SockAddr, sizeof(SockAddr));
	if (FAILURE == ret) {
		printf("Unable to connect to decryption server\n");
		close(sockfd);
		goto end;
	}

	sleep(1);
	ret = send(sockfd, &nextHop, sizeof(nextHop), 0);
	if (FAILURE == ret) {
		printf("Unable to send control information to decryption server\n");
		close(sockfd);
		goto end;
	}

	sendFile(sockfd, sendfile, size);

end:
	return;
}

void sendFile(int sockfd, char *filename, int size)
{
	FILE *fp;
	int ret;
	char *buf = NULL;

	fp = fopen(filename, "r");
	if (NULL == fp) {
		printf("Unable to open file : %s\n", filename);
		goto end;
	}

	buf = (char *) malloc(MAX_PKT_SIZE+1);

	sleep(1);
	while (size > 0) {

		ret = fread(buf, 1, MAX_PKT_SIZE, fp);

		ret = send(sockfd, buf, ret, 0);
		if (FAILURE == ret) {
			printf("unable to send file to decryption server\n");
			free(buf);
			goto end;
		}

		size -= ret;
	}

	free(buf);

end:
	return;
}

